<template>
	<el-dialog title="选择人员" :visible.sync="visible" append-to-body width="992px">
		<div class="sw_select_user" v-loading="loading">
			<div class="query_user_wrapper" v-loading="tableLoading">
				<el-form size="mini" inline>
					<el-form-item><el-input v-model="queryUser.account" placeholder="用户账号" style="width: 180px"></el-input></el-form-item>
					<el-form-item><el-input v-model="queryUser.userName" placeholder="用户姓名" style="width: 180px"></el-input></el-form-item>
					<el-form-item>
						<el-select v-model="queryUser.type" clearable placeholder="用户类型" style="width: 100px">
							<el-option v-for="(item, index) in dictEnums['USER_TYPE']" :key="index" :label="item.msg" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-select v-model="queryUser.sex" clearable placeholder="用户性别" style="width: 100px">
							<el-option v-for="(item, index) in dictEnums['USER_SEX']" :key="index" :label="item.msg" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item><el-button type="primary" @click="initTableData">查询</el-button></el-form-item>
				</el-form>
				<el-table ref="table" size="medium" row-key="id" :data="tableData" height="100%" @select="handleSelectTable" @select-all="handleAllSelectTable">
					<el-table-column type="selection" width="48" align="center"></el-table-column>
					<el-table-column prop="account" label="用户账号" width="180"></el-table-column>
					<el-table-column prop="userName" label="用户姓名" width="180"></el-table-column>
					<el-table-column prop="deptName" label="用户性别">
						<template slot-scope="{ row }">
							<dict-tag dict="USER_SEX" :data="row.sex"></dict-tag>
						</template>
					</el-table-column>
					<el-table-column prop="deptName" label="用户部门"></el-table-column>
					<el-table-column prop="type" label="用户类型" width="100">
						<template slot-scope="{ row }">
							<dict-tag dict="USER_TYPE" :data="row.type"></dict-tag>
						</template>
					</el-table-column>
				</el-table>
				<sw-pagination
					:layout="userPageLayout"
					:total="dataCount"
					:page.sync="queryUser.page"
					:limit.sync="queryUser.limit"
					@change="initTableData"
				></sw-pagination>
			</div>
			<div class="select_user_wrapper">
				<div class="list">
					<div class="item" v-for="(item, index) in checkedUser" :key="index">
						<el-avatar size="medium" shape="square" :src="squareUrl"></el-avatar>
						<h4>{{ item.userName }}</h4>
						<el-button size="medium" type="text" icon="el-icon-delete" @click="handleDeleteUser(item)"></el-button>
					</div>
				</div>
				<div class="button">
					<el-button size="small" @click="visible = false">取消</el-button>
					<el-button size="small" type="primary" :loading="btnLoading" @click="handleSubmitUser">确定</el-button>
				</div>
			</div>
		</div>
	</el-dialog>
</template>

<script>
import { mapGetters } from 'vuex';
import { getUserList } from '@/api/system/tbSysUser';
import { getUserByRole, addUsersByRole } from '@/api/system/tbSysUserRole';
export default {
	props: {
		value: {
			type: Boolean,
			default: false
		},
		roleId: String
	},
	data() {
		return {
			loading: false,
			tableLoading: false,
			visible: this.value,
			userPageLayout: 'slot, prev, pager, next',
			squareUrl: require('@/assets/img/avatar_image.png'),
			dataCount: 0,
			queryUser: { page: 1, limit: 10 },
			tableData: [],
			checkedUser: [],
			btnLoading: false,
			originalChecked: []
		};
	},
	computed: {
		...mapGetters(['dictEnums'])
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		async visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.loading = true;
			await this.getUserByRoleData();
			await this.initTableData();
			this.loading = false;
		},
		tableData(arr) {
			this.$nextTick(() => {
				this.$refs['table'].clearSelection();
				this.checkedUser.forEach((item) => {
					let info = arr.find((n) => n.id === item.id);
					!!info && this.$refs['table'].toggleRowSelection(info, true);
				});
			});
		}
	},
	methods: {
		//初始化表格数据
		async initTableData() {
			if (!this.loading) {
				this.tableLoading = true;
			}
			await this.getTabelData();
			this.tableLoading = false;
		},

		//获取用户列表
		async getTabelData() {
			let params = { ...this.queryUser };
			let result = await getUserList(params).then((res) => res.data);
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.tableData = !result.data ? [] : result.data;
			}
		},

		//获取用户通过角色
		async getUserByRoleData() {
			let result = await getUserByRole(this.roleId).then((res) => res.data);
			if (result.code === '0') {
				let datas = !result.data ? [] : result.data;
				this.checkedUser = datas.map((item) => {
					return { id: item.userId, userName: item.userName || '导入用户' };
				});
				this.originalChecked = this.$lodash.cloneDeep(this.checkedUser);
			}
		},

		//全选用户
		handleAllSelectTable(selection) {
			let curCheckeds = selection.map((item) => item.id);
			let checkedUsers = this.checkedUser.map((item) => item.id);
			if (curCheckeds.length > 0) {
				let diffChecked = this.$lodash.difference(curCheckeds, checkedUsers);
				diffChecked.forEach((item) => {
					let info = selection.find((n) => n.id === item);
					this.checkedUser.push({ id: item, userName: info.userName });
				});
			} else {
				this.tableData.forEach((item) => {
					let index = this.checkedUser.findIndex((n) => n.id === item.id);
					this.checkedUser.splice(index, 1);
				});
			}
		},

		//选择用户
		handleSelectTable(selection, data) {
			let checkedUsers = this.checkedUser.map((item) => item.id);
			let index = checkedUsers.findIndex((n) => n === data.id);
			if (selection.some((n) => n.id === data.id) && index === -1) {
				this.checkedUser.push({ id: data.id, userName: data.userName });
			} else if (index !== -1) {
				this.checkedUser.splice(index, 1);
			}
		},

		//删除选中用户
		handleDeleteUser(data) {
			let index = this.checkedUser.findIndex((item) => item.id === data.id);
			this.checkedUser.splice(index, 1);
			if (this.tableData.some((item) => item.id === data.id)) {
				let info = this.tableData.find((item) => item.id === data.id);
				this.$refs['table'].toggleRowSelection(info, false);
			}
		},

		//提交选中用户
		async handleSubmitUser() {
			let params = { roleId: this.roleId };
			let curChecked = this.checkedUser.map((item) => item.id);
			let originalChecked = this.originalChecked.map((item) => item.id);
			let diffChecked = this.$getArrDifference(curChecked, originalChecked);
			console.log(curChecked);
			console.log(diffChecked);
			console.log(originalChecked);
			params['userList'] = diffChecked.map((item) => {
				let obj = { relId: item };
				if (originalChecked.indexOf(item) === -1) {
					obj['operType'] = '1';
				} else {
					obj['operType'] = '2';
				}
				return obj;
			});
			/* this.btnLoading = true;
			await this.updateSelectedUser(params);
			this.btnLoading = false; */
		},

		//更新选中用户
		async updateSelectedUser(params) {
			let result = await addUsersByRole(params).then((res) => res.data);
			if (result.code === '0') {
				this.visible = false;
				this.$showCustomMessage('success', `更新选中用户成功`);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.sw_select_user {
	display: flex;
	height: calc(70vh - 72px);
	width: calc(100% + 30px);
	margin: -15px;
	overflow: hidden;
}

:deep(.query_user_wrapper) {
	display: flex;
	flex-direction: column;
	flex: 1;
	overflow: hidden;

	.el-form {
		padding: 10px;

		.el-input {
			display: flex;
		}
	}

	.el-form-item {
		margin-bottom: 0;
	}

	.el-form-item__content {
		display: flex;
		align-items: center;
	}

	.el-table {
		border-top: solid 1px #e5e5e5;
	}

	.sw-pagination {
		padding: 12px;
		margin-top: 0;
	}
}

.select_user_wrapper {
	display: flex;
	flex-direction: column;
	width: 240px;
	flex-shrink: 0;
	border-left: solid 1px #e5e5e5;

	.list {
		flex: 1;
		padding: 4px 0;
		overflow: auto;
		border-bottom: solid 1px #e5e5e5;
	}

	.item {
		display: flex;
		align-items: center;
		padding: 6px 10px;

		.el-avatar {
			flex-shrink: 0;
		}

		h4 {
			flex: 1;
			font-size: 14px;
			margin-left: 10px;
			overflow: hidden;
		}

		.el-button {
			flex-shrink: 0;
		}

		.el-button {
			flex-shrink: 0;
		}
	}

	.button {
		padding: 10px;
		text-align: right;
	}
}
</style>
